<template>
  <div class="design-container">
    <h1 class="page-title">教学设计生成</h1>
    
    <!-- 输入区 -->
    <div class="input-section" v-if="!isGenerating && !designResult">
      <div class="form-group">
        <label>课程名称</label>
        <input 
          type="text" 
          v-model="formData.courseName" 
          placeholder="请输入课程名称，如：人工智能概述"
        >
      </div>
      
      <div class="form-group">
        <label>教学目标</label>
        <div class="objective-tabs">
          <div 
            v-for="tab in objectiveTabs" 
            :key="tab.value"
            :class="['tab', { active: formData.objectiveType === tab.value }]"
            @click="selectObjectiveType(tab.value)"
          >
            {{ tab.label }}
          </div>
        </div>
        
        <textarea 
          v-if="formData.objectiveType === 'custom'"
          v-model="formData.objective"
          placeholder="请输入自定义教学目标描述"
          rows="4"
        ></textarea>
        <div v-else class="objective-preview">
          {{ getObjectivePreview() }}
        </div>
      </div>
      
      <div class="form-group">
        <label>授课时长（分钟/课时）</label>
        <input 
          type="number" 
          v-model.number="formData.duration" 
          placeholder="45"
          min="1"
          max="180"
        >
      </div>
      
      <div class="form-group">
        <label>授课风格</label>
        <select v-model="formData.teachingStyle">
          <option value="">请选择授课风格</option>
          <option 
            v-for="style in teachingStyles" 
            :key="style.value" 
            :value="style.value"
          >
            {{ style.label }}
          </option>
        </select>
      </div>
      
      <button 
        class="generate-btn" 
        :disabled="!isFormValid" 
        @click="generateDesign"
      >
        确认输入，生成教学设计
      </button>
    </div>
    
    <!-- 加载状态 -->
    <div class="loading-section" v-if="isGenerating">
      <div class="loading-spinner"></div>
      <p>正在生成教学设计，请稍候...</p>
    </div>
    
    <!-- 结果预览区 -->
    <div class="result-section" v-if="designResult">
      <div class="result-header">
        <h2>{{ designResult.courseName }} 教学设计</h2>
        <p class="time">生成时间：{{ designResult.createdAt }}</p>
      </div>
      
      <div class="result-content">
        <!-- 教学环节 -->
        <div class="result-block">
          <h3>教学环节</h3>
          <div class="teaching-steps">
            <div 
              v-for="(step, index) in designResult.teachingSteps" 
              :key="index"
              class="step-item"
            >
              <div class="step-time">{{ step.time }}分钟</div>
              <div class="step-content">
                <div class="step-name">{{ step.name }}</div>
                <div class="step-desc">{{ step.description }}</div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 教学方法 -->
        <div class="result-block">
          <h3>教学方法</h3>
          <div class="method-list">
            <div 
              v-for="(method, index) in designResult.teachingMethods" 
              :key="index"
              class="method-item"
            >
              <div class="method-icon">{{ index + 1 }}</div>
              <div>
                <div class="method-name">{{ method.name }}</div>
                <div class="method-desc">{{ method.description }}</div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 教学重难点 -->
        <div class="result-block">
          <h3>教学重难点</h3>
          <div class="points-container">
            <div class="points-block">
              <h4>重点</h4>
              <ul class="points-list">
                <li v-for="(point, index) in designResult.keyPoints" :key="index">
                  {{ point }}
                </li>
              </ul>
            </div>
            
            <div class="points-block">
              <h4>难点</h4>
              <ul class="points-list">
                <li v-for="(point, index) in designResult.difficultyPoints" :key="index">
                  {{ point }}
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
      
      <div class="result-actions">
        <button class="action-btn edit" @click="editDesign">编辑</button>
        <button class="action-btn save" @click="saveDesign">保存</button>
        <button class="action-btn export" @click="exportDesign">打印/导出</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useResourceStore } from '../../stores/resourceStore'
import apiService from '../../api'

const router = useRouter()
const resourceStore = useResourceStore()

// 表单数据
const formData = ref({
  courseName: '',
  objectiveType: 'knowledge',
  objective: '',
  duration: 45,
  teachingStyle: ''
})

// 教学目标标签
const objectiveTabs = [
  { label: '知识传授', value: 'knowledge' },
  { label: '技能培养', value: 'skill' },
  { label: '素质提升', value: 'quality' },
  { label: '自定义', value: 'custom' }
]

// 授课风格选项
const teachingStyles = [
  { label: '案例驱动', value: 'case_driven' },
  { label: '理论精讲', value: 'theory_focused' },
  { label: '互动式教学', value: 'interactive' },
  { label: '项目式学习', value: 'project_based' },
  { label: '探究式教学', value: 'inquiry_based' }
]

// 状态变量
const isGenerating = ref(false)
const designResult = ref(null)

// 表单验证
const isFormValid = computed(() => {
  return (
    formData.value.courseName.trim() !== '' &&
    ((formData.value.objectiveType === 'custom' && formData.value.objective.trim() !== '') ||
     formData.value.objectiveType !== 'custom') &&
    formData.value.duration > 0 &&
    formData.value.teachingStyle !== ''
  )
})

// 选择教学目标类型
const selectObjectiveType = (type) => {
  formData.value.objectiveType = type
  // 如果不是自定义，清空自定义输入
  if (type !== 'custom') {
    formData.value.objective = ''
  }
}

// 获取教学目标预览文本
const getObjectivePreview = () => {
  const typeMap = {
    knowledge: '通过本课程，学生将掌握相关概念和理论知识，理解核心原理，能够解释和应用所学内容。',
    skill: '通过本课程，学生将培养实际操作能力，掌握相关技能，能够独立完成相关任务。',
    quality: '通过本课程，学生将提升综合素质，培养批判性思维、创新意识和团队协作精神。'
  }
  return typeMap[formData.value.objectiveType] || ''
}

// 生成教学设计
const generateDesign = async () => {
  try {
    isGenerating.value = true
    
    // 准备请求参数
    const params = {
      courseName: formData.value.courseName,
      objective: formData.value.objectiveType === 'custom' 
        ? formData.value.objective 
        : getObjectivePreview(),
      duration: formData.value.duration,
      teachingStyle: formData.value.teachingStyle
    }
    
    // 调用API生成教学设计
    // 实际项目中应该调用后端API
    // const response = await apiService.design.generate(params)
    
    // 模拟API响应
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 模拟返回数据
    const mockResponse = {
      courseName: params.courseName,
      objective: params.objective,
      duration: params.duration,
      teachingStyle: params.teachingStyle,
      teachingSteps: [
        {
          name: '导入新课',
          time: 5,
          description: '通过提问和案例引入，激发学生学习兴趣'
        },
        {
          name: '讲解新知识',
          time: 20,
          description: '讲解核心概念和原理，结合实例深入分析'
        },
        {
          name: '互动讨论',
          time: 10,
          description: '学生分组讨论应用场景，教师巡视指导'
        },
        {
          name: '巩固练习',
          time: 8,
          description: '完成相关练习，检验学习效果'
        },
        {
          name: '总结归纳',
          time: 2,
          description: '归纳本节课重点内容，布置课后作业'
        }
      ],
      teachingMethods: [
        {
          name: '讲授法',
          description: '系统讲解理论知识和概念'
        },
        {
          name: '案例分析法',
          description: '通过典型案例深化理解'
        },
        {
          name: '小组讨论法',
          description: '促进学生思维碰撞和知识内化'
        }
      ],
      keyPoints: [
        '人工智能的基本概念和发展历程',
        '人工智能的主要技术路线和方法',
        '人工智能的典型应用场景'
      ],
      difficultyPoints: [
        '理解人工智能与传统编程的区别',
        '掌握人工智能算法的基本原理'
      ],
      createdAt: new Date().toLocaleString()
    }
    
    // 设置结果
    designResult.value = mockResponse
    
    // 保存到状态管理
    resourceStore.setDesignData(mockResponse)
    
  } catch (error) {
    console.error('生成教学设计失败:', error)
    // 可以在这里添加错误提示
  } finally {
    isGenerating.value = false
  }
}

// 编辑设计
const editDesign = () => {
  // 将当前结果数据填充到表单中
  formData.value.courseName = designResult.value.courseName
  formData.value.objectiveType = 'custom'
  formData.value.objective = designResult.value.objective
  formData.value.duration = designResult.value.duration
  formData.value.teachingStyle = designResult.value.teachingStyle
  
  // 清空结果，返回编辑状态
  designResult.value = null
}

// 保存设计
const saveDesign = async () => {
  try {
    // 调用API保存设计
    // 实际项目中应该调用后端API
    // await apiService.resource.save({
    //   type: 'design',
    //   data: designResult.value
    // })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 显示成功提示
    alert('教学设计已保存到资源库')
    
  } catch (error) {
    console.error('保存教学设计失败:', error)
    // 可以在这里添加错误提示
  }
}

// 导出设计
const exportDesign = async () => {
  try {
    // 调用API导出设计
    // 实际项目中应该调用后端API
    // const response = await apiService.design.export(designResult.value.id)
    // 
    // // 创建下载链接
    // const url = window.URL.createObjectURL(new Blob([response]))
    // const link = document.createElement('a')
    // link.href = url
    // link.setAttribute('download', `${designResult.value.courseName}_教学设计.pdf`)
    // document.body.appendChild(link)
    // link.click()
    // document.body.removeChild(link)
    
    // 模拟导出功能
    alert('导出功能在实际项目中需要后端支持')
    
  } catch (error) {
    console.error('导出教学设计失败:', error)
    // 可以在这里添加错误提示
  }
}

// 页面加载时检查是否有已生成的设计数据
onMounted(() => {
  const savedDesign = resourceStore.getDesignData
  if (savedDesign && savedDesign.courseName) {
    designResult.value = savedDesign
  }
})
</script>

<style scoped>
.design-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.page-title {
  font-size: 1.8rem;
  margin-bottom: 24px;
  color: #333;
  font-weight: 600;
}

/* 输入区样式 */
.input-section {
  background-color: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

input[type="text"],
input[type="number"],
textarea,
select {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.3s;
}

input[type="text"]:focus,
input[type="number"]:focus,
textarea:focus,
select:focus {
  border-color: #4b6cb7;
  outline: none;
}

/* 教学目标标签样式 */
.objective-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.tab {
  padding: 8px 16px;
  border-radius: 20px;
  background-color: #f5f5f5;
  color: #666;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 0.9rem;
}

.tab.active {
  background-color: #4b6cb7;
  color: white;
}

.objective-preview {
  padding: 12px;
  background-color: #f9f9f9;
  border-radius: 6px;
  color: #666;
  font-size: 0.95rem;
  line-height: 1.5;
}

/* 生成按钮样式 */
.generate-btn {
  width: 100%;
  padding: 12px;
  background-color: #4b6cb7;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.generate-btn:hover {
  background-color: #3b5998;
}

.generate-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

/* 加载状态样式 */
.loading-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid rgba(75, 108, 183, 0.1);
  border-radius: 50%;
  border-top-color: #4b6cb7;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 结果预览区样式 */
.result-section {
  background-color: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.result-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.result-header h2 {
  margin: 0 0 8px 0;
  font-size: 1.5rem;
  color: #333;
}

.result-header .time {
  margin: 0;
  font-size: 0.9rem;
  color: #999;
}

.result-block {
  margin-bottom: 30px;
}

.result-block h3 {
  font-size: 1.2rem;
  margin: 0 0 16px 0;
  color: #333;
  font-weight: 600;
}

/* 教学环节样式 */
.teaching-steps {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.step-item {
  display: flex;
  background-color: #f9f9f9;
  border-radius: 8px;
  overflow: hidden;
}

.step-time {
  background-color: #4b6cb7;
  color: white;
  padding: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 80px;
  font-weight: 500;
}

.step-content {
  padding: 12px 16px;
  flex: 1;
}

.step-name {
  font-weight: 500;
  margin-bottom: 4px;
  color: #333;
}

.step-desc {
  font-size: 0.9rem;
  color: #666;
}

/* 教学方法样式 */
.method-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.method-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.method-icon {
  width: 28px;
  height: 28px;
  background-color: #4b6cb7;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.9rem;
  font-weight: 500;
}

.method-name {
  font-weight: 500;
  margin-bottom: 4px;
  color: #333;
}

.method-desc {
  font-size: 0.9rem;
  color: #666;
}

/* 教学重难点样式 */
.points-container {
  display: flex;
  gap: 24px;
  flex-wrap: wrap;
}

.points-block {
  flex: 1;
  min-width: 250px;
}

.points-block h4 {
  margin: 0 0 12px 0;
  font-size: 1.1rem;
  color: #333;
}

.points-list {
  margin: 0;
  padding-left: 20px;
}

.points-list li {
  margin-bottom: 8px;
  color: #555;
  line-height: 1.5;
}

/* 结果操作按钮样式 */
.result-actions {
  display: flex;
  gap: 12px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.action-btn {
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 0.95rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
}

.action-btn.edit {
  background-color: #f5f5f5;
  color: #666;
}

.action-btn.edit:hover {
  background-color: #e0e0e0;
}

.action-btn.save {
  background-color: #4b6cb7;
  color: white;
}

.action-btn.save:hover {
  background-color: #3b5998;
}

.action-btn.export {
  background-color: #f0f5ff;
  color: #4b6cb7;
  border: 1px solid #4b6cb7;
}

.action-btn.export:hover {
  background-color: #e6f0ff;
}

/* 响应式调整 */
@media (max-width: 600px) {
  .points-container {
    flex-direction: column;
  }
  
  .result-actions {
    flex-direction: column;
  }
  
  .action-btn {
    width: 100%;
  }
}
</style>